import React, { Fragment } from 'react';
import { Link, Redirect, Switch, Route } from 'dva/router';
import DocumentTitle from 'react-document-title';
import { Icon } from 'antd';
import GlobalFooter from '../components/GlobalFooter';
import styles from './UserLayout.less';
import { getRoutes, getPageQuery, getQueryPath } from '../utils/utils';
import { title as Title } from '../title';

const copyright = (
    <Fragment>
        Copyright <Icon type="copyright" />{Title}
    </Fragment>
);

function getLoginPathWithRedirectPath() {
    const params = getPageQuery();
    const { redirect } = params;
    return getQueryPath('/user/login', {
        redirect,
    });
}

class UserLayout extends React.PureComponent {
    getPageTitle(options = {}) {
        const { routerData, location } = this.props;
        const { pathname } = location;
        const { isNav = false } = options;
        let title = Title;
        const currentRouterName = routerData[pathname] && routerData[pathname].name;

        if (!currentRouterName) return '';

        if (isNav) {
            title = currentRouterName;
        }

        if (!isNav) {
            title = `${currentRouterName} - ${Title}`;
        }

        return title;
    }

    render() {
        const { routerData, match } = this.props;
        return (
            <DocumentTitle title={this.getPageTitle()}>
                <div className={styles.container}>
                    <div className={styles.content}>
                        <div className={styles.header}>
                            <Link to="/" className="link">
                                {Title}
                            </Link>
                            <p>{this.getPageTitle({ isNav: true })}</p>
                        </div>
                        <Switch>
                            {getRoutes(match.path, routerData).map(item => (
                                <Route
                                    key={item.key}
                                    path={item.path}
                                    component={item.component}
                                    exact={item.exact}
                                />
                            ))}
                            <Redirect from="/user" to={getLoginPathWithRedirectPath()} />
                        </Switch>
                    </div>
                    <GlobalFooter copyright={copyright} />
                </div>
            </DocumentTitle>
        );
    }
}

export default UserLayout;
